<template>
  <div class="callback-container">
    <div class="callback-box">
      <el-loading v-if="loading" text="正在登录中..." />
      <div v-else-if="error" class="error-message">
        <el-icon :size="48" color="#f56c6c"><CircleClose /></el-icon>
        <p>{{ error }}</p>
        <el-button type="primary" @click="goToLogin">返回登录</el-button>
      </div>
      <div v-else class="success-message">
        <el-icon :size="48" color="#67c23a"><CircleCheck /></el-icon>
        <p>登录成功</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { CircleClose, CircleCheck } from '@element-plus/icons-vue'
import { authAPI } from '../api/index.js'

const router = useRouter()
const route = useRoute()

const loading = ref(true)
const error = ref('')

onMounted(async () => {
  // 从URL参数中获取code
  const code = route.query.code
  
  if (!code) {
    error.value = '未收到授权码，请重试'
    loading.value = false
    return
  }
  
  try {
    // 调用后端接口进行登录
    const response = await authAPI.dingTalkCallback({ code })
    
    if (response.access_token) {
      // 保存token和用户信息
      localStorage.setItem('token', response.access_token)
      localStorage.setItem('userInfo', JSON.stringify(response.user_info || {}))
      
      ElMessage.success('登录成功')
      loading.value = false
      
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        router.push('/home')
      }, 1000)
    } else {
      error.value = response.message || '登录失败'
      loading.value = false
    }
  } catch (err) {
    error.value = err.response?.data?.detail || '登录失败，请重试'
    loading.value = false
  }
})

const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.callback-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.callback-box {
  background: white;
  border-radius: 16px;
  padding: 60px 40px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
  text-align: center;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.error-message p,
.success-message p {
  margin: 20px 0;
  font-size: 16px;
  color: #333;
}

.error-message {
  color: #f56c6c;
}

.success-message {
  color: #67c23a;
}
</style>








